﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Mammoth.Entities;
using Mammoth.Navigations;
using Mammoth.Services;
using Mammoth.Events;

namespace Mammoth.ViewModels
{
    public class AddAccountFormViewModel : WPFViewModelBase
    {
        IGTalkService Service;
        IGTalkConfiguration Configuration;

        public string Email { get; set; }
        public string Password { get; set; }
        public bool IsAutoLogin { get; set; }

        public AddAccountFormViewModel(IInputElement dispatcher, IGTalkService service, IGTalkConfiguration configuration) 
            : this(dispatcher, service, configuration, null) { }
        public AddAccountFormViewModel(IInputElement dispatcher, IGTalkService service, IGTalkConfiguration configuration, object arguments)
            : base(dispatcher)
        {
            Service = service;
            Configuration = configuration;
            IsAutoLogin = true;
            if (arguments != null)
                EditAccount(((AddAccountArguments)arguments).Email);
        }

        void EditAccount(string email)
        {
            foreach (var item in Configuration.Accounts)
            {
                if (item.Email == email)
                {
                    Email = item.Email;
                    Password = item.Password;
                    IsAutoLogin = item.IsAutoLogin;
                    break;
                }
            }
        }

        public void Save()
        {
            try
            {
                if (!Validate()) return;
                Service.AddAccount(Email, Password, IsAutoLogin);
                Dispatcher.RaiseNavigationEvent();
            }
            catch (Exception ex)
            {
                Dispatcher.RaiseErrorEvent(ex.Message);
            }
        }
    }
}
